<?php
/******************************************************
v4 - Management Framework
Copyright (C) 2008  Gary Taylor, gMerc Incorporation
http://www.gmerc.com/v4/

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

gary@gmerc.com
******************************************************/
class master {
/***************************************************************************************/
/* PAGE LOADING FUNCTIONS */
/***************************************************************************************/
  function loadpage() {

    $mod=$this->site['page'];
    $sourcelibpath=$this->mainconfig['v4sourcedir'].$this->mainconfig['sourcedirectory'].$this->site['dirpath'].$mod.'.lib.php';
    $modulelibpath=$this->mainconfig['v4moduledir'].$mod.'.lib.php';
    if (is_file($sourcelibpath)) { $libpath=$sourcelibpath; } else
     if (is_file($modulelibpath)) { $libpath=$modulelibpath; } else { echo "NO MODULE!".$mod.'<br>Source: '.$sourcelibpath.'<br>Module: '.$modulelibpath.'<br><pre>';print_r($this);echo '</pre>';exit(); }

    require $libpath;
    $this->allclasses[$mod] = new $mod();
    if (is_callable(array($this->allclasses[$mod], 'loaddata'))) { $this->allclasses[$mod]->loaddata(); }

    return;
  }
  function loadmodule($mod,$modpath='') {
    global $masterclass;

    if ($modpath=='') { $modpath=$masterclass->mainconfig['v4moduledir'].$mod.'/'.$mod.'.func.php'; }
    if (is_file($modpath)) {
      if (!isset($masterclass->allclasses[$mod])) {
        require $modpath;
        $masterclass->allclasses[$mod]=new $mod;
      }
    } else {
      echo 'Fatal Error: '.$modpath.' Does Not Exist';exit();
    }

  return;
  }
  function loadjavascript($functionmodule,$jspath='') {
    global $masterclass;

    if ($jspath=='') { $jspath=$masterclass->mainconfig['v4moduledir'].$functionmodule.'/'.$functionmodule.'.js'; }
    if (is_file($jspath)) {
      $masterclass->websiteconfig['javascript_static'].="\n".file_get_contents($jspath);
    } else { echo $jspath.' - Does Not Exist!'; }
        

  return;
  }
  function loadpostfields() {
    $postfields=array();
    if (!empty($postfields)) {
    foreach ($this->site['postfields'] as $tabledata) {
      if (isset($tabledata['fields'])) {
        foreach ($tabledata['fields'] as $dbname=>$fieldname) {
          $postfields[]=$fieldname;
        }
      }
    }
    }
  return $postfields;
  }
  function loadtrackingfields() {
    $trackingfields=array();
    if (isset($this->site['postfields']) && !empty($this->site['postfields'])) {
      foreach ($this->site['postfields'] as $postdata) {
        if (isset($postdata['trackingid']) && !in_array($postdata['trackingid'],$trackingfields)) { $trackingfields[]=$postdata['trackingid']; }
      }
    }

    return $trackingfields;
  }
  function loadtrackingvalues_table($table,$trackingid) {
    $trackingfields=$this->loadtrackingfields();
    if (empty($trackingfields)) { return; }
    
    $strsql = sprintf("SELECT * FROM `%s` WHERE `id`=%d",$this->format_str($table),$this->format_dbl($trackingid));
    $rs=$this->allclasses['adodb']->GetRow($strsql);
    if (!empty($rs)) {
      foreach ($trackingfields as $trackingfield) {
        $trackingcol=substr($trackingfield,0,strlen($trackingfield)-2);
        if (!isset($masterclass->sitevars[$trackingfield]) && isset($rs[$trackingcol])) { $masterclass->sitevars[$trackingfield]=$rs[$trackingcol]; }   
      }
    }

  return;    
  }
  function loadformvars($vars) {
    foreach ($vars as $sqlinfo) {
      if (isset($sqlinfo['table']) && $this->sitevars[$sqlinfo['trackingid']]>0) {
        $strsql = sprintf("SELECT * FROM `%s` WHERE `id`=%d",
        $this->format_str($sqlinfo['table']),
        $this->format_dbl($this->sitevars[$sqlinfo['trackingid']])
        );
        $forminfo=$this->allclasses['adodb']->GetRow($strsql);
        foreach ($sqlinfo['fields'] as $tablefield=>$formname) {
          $this->sitevars[$formname]=$forminfo[$tablefield];
        }
      }
    }
  }
  function load_config($userfile) {
    global $masterclass;

    unset($userconfig);
    if (is_file($userfile)) {
      include $userfile;
      $arrconfig=$userconfig;
      
      unset($userconfig);
    }
  return $arrconfig;
  }

  function savedata() {
    global $masterclass;

    if (!empty($masterclass->site['postfields'])) {
      foreach($masterclass->site['postfields'] as $dbinfo) {
        $masterclass->uploaddata($dbinfo);
      }
    }
  return;
  }

  function uploaddata($dbinfo) {
    global $masterclass;

      if (isset($dbinfo['table'])) {
        if (!isset($masterclass->sitevars[$dbinfo['trackingid']])) {
          $masterclass->sitevars[$dbinfo['trackingid']]=$masterclass->db_insert($dbinfo);
        } else {

          $checkrecord=$this->checkid($dbinfo['table'],$masterclass->sitevars[$dbinfo['trackingid']]);
          if ($checkrecord=='') {
            $masterclass->sitevars[$dbinfo['trackingid']]=$masterclass->db_insert($dbinfo);
          } else {
            $masterclass->db_update($dbinfo);
          }
        }
      }

  return;
  }

  function deletedata($deletefields) {
    global $masterclass;
    if (!empty($deletefields)) {
      foreach($deletefields as $dbinfo) {
        $masterclass->db_delete($dbinfo);
      }
    }
  return;
  }



/***************************************************************************************/
/* CHECK PERMISSION */
/***************************************************************************************/
  function check_permission($inp='',$lvl='',$cdirpath='',$cpage='') {
   global $masterclass;

    switch ($lvl) {
     case 'field':
      $returnauth=$masterclass->unify_permissionvalue($masterclass->site['defaultfieldpermission']);
     break;
     case 'page':
      $returnauth=$masterclass->unify_permissionvalue($masterclass->site['defaultpagepermission']);
     break;
    }

    if (isset($masterclass->allclasses['authentication'])) {;
      $authpermissioncall=$masterclass->site['authentication_type'].'check_permission';
      if (is_callable(array($masterclass->allclasses['authentication'],$authpermissioncall))) {
        $authpermission=$masterclass->allclasses['authentication']->$authpermissioncall($inp,$lvl,$cdirpath,$cpage);
        if ($authpermission!='') { $returnauth=$authpermission; }
      }
    }

    if (isset($masterclass->site['page'])) {
      if (is_callable(array($masterclass->allclasses[$masterclass->site['page']],check_permission))) {
        $modpermission=$masterclass->allclasses[$masterclass->site['page']]->check_permission($inp,$lvl,$cdirpath,$cpage);
        if ($modpermission!='') { $returnauth=$modpermission; }
      }
    }

    if ($masterclass->site['defaultpermission']!='') { $returnauth=$masterclass->unify_permissionvalue($masterclass->site['defaultpermission']); }
  return $returnauth;
  }
  function unify_permissionvalue($val) {
    switch ($val) {
     case false:
     case '0':
     case 'no':
     case 'deny':
     case 'fuckoff':
      return '0';
     break;
     case true:
     case '1':
     case 'yes':
     case 'allow':
     case 'fuckyeah':
      return '1';
     break;
    }
  return false;
  }
  function swap_permissionvalue($val) {
   if ($val=='0') {
    return '1';
   } else {
    return '0';
   }
  }



/***************************************************************************************/
/* MYSQL DATA MANAGEAGEMENT */
/***************************************************************************************/
  function db_delete($dbinfo) {
    global $masterclass;

    if (!isset($dbinfo['table'])) { return false; }
    $strsql = "DELETE FROM `".$dbinfo['table']."` ";
    $strsql.=" WHERE ".$dbinfo['strwhere']." ";
    $this->allclasses['adodb']->Execute($strsql);

  return;
  }
  function db_update($dbinfo) {
    global $masterclass;

    if (!isset($dbinfo['table']) || (!isset($dbinfo['trackingid']) && !isset($dbinfo['staticid'])) || (!isset($dbinfo['fields']) && !isset($dbinfo['static']))) { return false; }

    if (isset($dbinfo['trackingid'])) {
      $updatewhere=sprintf("`id`=%d",$this->format_str($masterclass->sitevars[$dbinfo['trackingid']]));
    } else if (isset($dbinfo['staticid'])) {
      $updatewhere=$this->format_str($dbinfo['staticid']);  
    }
    
    
    $updatefields=array();
    if (isset($dbinfo['fields']) && !empty($dbinfo['fields'])) {
      foreach ($dbinfo['fields'] as $dbcolumn => $sitevar) {
        $dbcolumn=$this->format_str($dbcolumn);
        $updatefields[$dbcolumn]=$this->format_str($masterclass->sitevars[$sitevar]);
      }
    }

    if (isset($dbinfo['static']) && !empty($dbinfo['static'])) {
      foreach ($dbinfo['static'] as $dbcolumn => $static) {
        $dbcolumn=$this->format_str($dbcolumn);
        $updatefields[$dbcolumn]=$this->format_str($static);
      }
    }
    
    $updatefields['updated']=date("Y-m-d H:i:s");

    $this->allclasses['adodb']->AutoExecute($dbinfo['table'],$updatefields,'UPDATE',$updatewhere);

  return;
  }
  function db_insert($dbinfo) {
    global $masterclass;
    if (!isset($dbinfo['table'])) { return false; }

    $insertfields=array();

    if (isset($dbinfo['fields']) && !empty($dbinfo['fields'])) {
      foreach ($dbinfo['fields'] as $dbcolumn => $sitevar) {
        $dbcolumn=$this->format_str($dbcolumn);
        $insertfields[$dbcolumn]=$this->format_str($masterclass->sitevars[$sitevar]);
      }
    }
    if (isset($dbinfo['static']) && !empty($dbinfo['static'])) {
      foreach ($dbinfo['static'] as $dbcolumn => $static) {
        $dbcolumn=$this->format_str($dbcolumn);
        $insertfields[$dbcolumn]=$this->format_str($static);
      }
    }
    
    $insertfields['updated']=date("Y-m-d H:i:s");
    $insertfields['datestamp']=date("Y-m-d H:i:s");

    $this->allclasses['adodb']->AutoExecute($dbinfo['table'],$insertfields,'INSERT');
    $trackingid=$this->allclasses['adodb']->Insert_ID();
    
    return $trackingid;
  }
  function mysql_trackrecord_where() {
    global $masterclass;

    $strsql='';
    $strsql.=sprintf(" (`trackingvar`='%s' AND (`trackingid`=%d OR `trackingid`=-1)) ",$this->format_str($masterclass->site['trackingvar']),$this->format_str($masterclass->site[$masterclass->site['trackingvar']]));
    $grouplist=$masterclass->fetch_groups($masterclass->site['trackingvar']);
    if (!empty($grouplist)) {
      $strgroupsql='';
      foreach ($grouplist as $gl) {
        if ($strgroupsql!='') { $strgroupsql.=' OR '; }
        $strgroupsql.=sprintf(" (`trackingvargroup`='%s' AND (`trackingidgroup`=%d OR `trackingidgroup`=-1)) ",$this->format_str($masterclass->site['trackingvar']),$this->format_dbl($gl['id']));
      }
      $strsql.=' OR ( '.$strgroupsql.' ) ';
    }

  return $strsql;
  }


/***************************************************************************************/
/* MISC FUNCTIONS */
/***************************************************************************************/
  function checkid($table,$id) {
    global $masterclass;

    $strsql = sprintf("SELECT `id` FROM %s WHERE `id`=%d",
    $this->format_str($table),
    $this->format_dbl($id)
    );
    $checkid=$this->allclasses['adodb']->GetOne($strsql);

  return $checkid;
  }
  function checkloginuser($username) {
    global $masterclass;
    
    $strsql = sprintf("SELECT `id` FROM `logins` WHERE `username`='%s'",$this->format_str($username));
    $checklogin=$this->allclasses['adodb']->GetOne($strsql);
    if ($checklogin!='') { return true; } else { return false; }
  
  return false;
  }
  function fetch_recordcount($table,$strwhere) {
    global $masterclass;

    $table=$this->format_str($table);
    $strwhere=$strwhere;
    $cnt=1;
      
    switch ($this->mainconfig['datastorage']) {
     case 'mysql':
      $cntsql="select count(*) as cnt FROM %s WHERE %s";
     break;
    }
    if ($cntsql!='') {  
      $cnt=$this->allclasses['adodb']->GetOne(sprintf($cntsql,$table,$strwhere));
    }
    return $cnt;
  }
  function fetch_records($strtable,$pg=0,$strwhere='',$strorderby='',$perpage=10,$strselect='*') {
    global $masterclass;

    $limits=-1;
    $limitc=-1;
    if (($pg>0) && ($pg!='' && $perpage!='')) {
     $limits=(($pg-1)*$perpage);
    }
    if ($perpage!='' && $perpage>0) { $limitc=$perpage; }

    $strsql = "SELECT ".$strselect." FROM ".$strtable." ";
    if ($strwhere!='') { $strsql.=" WHERE ".$strwhere." "; }
    if ($strorderby!='') { $strsql.=" ORDER BY ".$strorderby; }

    $returnlist=$this->allclasses['adodb']->SelectLimit($strsql,$limitc,$limits);
    
    if (!$returnlist) { echo $this->allclasses['adodb']->ErrorMsg(); }
    
  return $returnlist;
  }
  function fetch_groupid($uniquename,$groupname) {
    global $masterclass;

    $groupid=0;
    $strsql = sprintf("SELECT `id` FROM `trackgroups` WHERE `uniquelist`='%s' AND `name`='%s' ",$this->format_str($uniquename),$this->format_str($groupname));
    $groupid=$this->allclasses['adodb']->GetOne($strsql);

  return $groupid;
  }
  function fetch_grouptype($id) {
    global $masterclass;

    $grouptype='';
    $strsql = sprintf("SELECT `uniquelist` FROM `trackgroups` WHERE `id`=%d ",$this->format_dbl($id));
    $grouptype=$this->allclasses['adodb']->GetOne($strsql);
    
  return $grouptype;
  }
  function fetch_groups($uniquename='') {
    global $masterclass;

    $arrgroups=array();

    if ($uniquename!='') { $strwhere=sprintf(" `uniquelist`='%s' ",$this->format_str($uniquename)); }
    $strsql = "SELECT * FROM `trackgroups` ";
    if ($strwhere!='') { $strsql.=" WHERE ".$strwhere; }
    $strsql.=" ORDER BY `name` ";
    $arrgroups=$this->allclasses['adodb']->GetRow($strsql);

  return $arrgroups;
  }
  function fetch_group_members($id) {
    global $masterclass;

    $arrgroupmembers=array();
    if (isset($id) && $id>0) {
      $strsql = sprintf("SELECT `members` FROM `trackgroups` WHERE `id`=%d",$this->format_dbl($id));
      $arrgroupmembers=$this->allclasses['adodb']->GetOne($strsql);
      if ($groupmembers!='') {
        $arrgroupmembers = explode(',',substr($groupmembers,1,strlen($groupmembers)-2));
      }
    }
  return $arrgroupmembers;
  }
  function fetch_login($trackingvar,$trackingid) {
    global $masterclass;
    
    $arrlogin=array('login_user'=>'','login_pass'=>'');
    if ($trackingvar!='' && $trackingid>0) {
      $strsql = sprintf("SELECT `username`,`password` FROM `logins` WHERE `trackingvar`='%s' AND `trackingid`=%d",$this->format_str($trackingvar),$this->format_dbl($trackingid));
      $logininfo=$this->allclasses['adodb']->GetRow($strsql);
      if ($logininfo['username']!='') {
        $arrlogin['login_user']=$logininfo['username'];
        $arrlogin['login_pass']=$logininfo['password'];
      }
    }
      
  return $arrlogin;
  }
  
  function trackingvar_query() {
    global $masterclass;

    $ret='';
    $trackingvars=$this->loadtrackingfields();
    foreach ($trackingvars as $tv) {
      if (isset($masterclass->sitevars[$tv])) {
        if ($ret!='') { $ret.='&'; }
        $ret.=$tv.'='.$masterclass->sitevars[$tv];
      }
    }
  return $ret;
  }
  function urllocation_update($updateinfo=array()) {
    global $masterclass;

    if (empty($masterclass->sitevars['locationupdate'])) { return; }
    foreach ($masterclass->sitevars['locationupdate'] as $updateinfo) {
      if (!empty($updateinfo) && isset($updateinfo['dirpath']) && isset($updateinfo['page']) && isset($updateinfo['newlocation'])) {
        if ($masterclass->sitevars['dirpath']==$updateinfo['dirpath'] && $masterclass->sitevars['page']==$updateinfo['page']) {
          return $updateinfo['newlocation'];
        }
      }
    }

  return;
  }
  function get_string_between($string, $start, $end){
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
  }
  function add_unique_to_array($arrvalues,$arrtmp) {
    if (!is_array($arrvalues) || !is_array($arrtmp)) { return $arrvalues; }

    foreach ($arrtmp as $k=>$v) {
      if (!in_array($v,$arrvalues)) { array_push($arrvalues,$v); }
    }
    return $arrvalues;
  }
  function parsecommas($var) {
    $arrreturn=array();

    if (strpos($var,",")>0) {
      $arrreturn=explode(',',$var);
    } else {
      $arrreturn=array($var);
    }

    return $arrreturn;
  }
  function parse_csv($str,$delimiter=',',$enclosure='"',$len=0) {
    $fh = fopen('php://memory', 'rw');
    fwrite($fh, $str);
    rewind($fh);
    $result = fgetcsv($fh,$len,$delimiter,$enclosure);
    fclose($fh);
    return $result;
  }
  function displayhtmlvalue($val,$format=1) {
    switch ($format) {
     default:
     case 1:
      $val = htmlspecialchars($val,ENT_COMPAT);
     break;
     case 2:
      $val = htmlspecialchars($val,ENT_QUOTES);
     break;
     case 3:
      $val = htmlspecialchars($val,ENT_NOQUOTES);
     break;
     case 4:
      $val = addslashes($val);
     break;
     case 5:
      $val = htmlspecialchars($val,ENT_COMPAT);
      $val = addslashes($val);
     break;
    }
    return $val;
  }
  
  function deldirectorytree($f) {
    if (is_dir($f)) {
    $tmpdir=dir($f);
    while ($file = $tmpdir->read()) {
      if($file != "." && $file != "..") {
        if (is_dir($f.$file)) {
          $this->deldirectorytree($f.$file);
        } else {
          unlink($f.$file);
        }
      }
    }
    }
  }
  
  function format_javascript($str) {
    //$str = str_replace("\","\\",$str);
    $str = str_replace("'","\'",$str);
    $str = addslashes($str);
    $str = str_replace(chr(13).chr(10),"\\n",$str);
    //$str = nl2br($str);
    //$str = str_replace("/","\/",$str);
    //$str = str_replace(chr(34),"\".chr(34),$str);
    return $str;
  }

  function format_str($str) {
    $tmpstr=$str;
    
	$tmpstr = htmlentities($tmpstr, ENT_QUOTES);
  	
	if (get_magic_quotes_gpc()) { 
		$tmpstr = stripslashes($tmpstr); 
	}
  	
 	$tmpstr = strip_tags($tmpstr);
	$tmpstr = str_replace("\r\n", "", $tmpstr);
    
    return $tmpstr;
  }
  function format_dbl($str) {
    $tmpstr='';
    $tmpstr=preg_replace("/[^0-9\.]/",'',$str);

    return $tmpstr;
  }
  function format_money($amt) {

    $amt=preg_replace('/[^\d|\.]/','',$amt);
    $arramt=explode('.',$amt.'.'); 
    $amt=$arramt[0].'.';
    if ($arramt[1]!='') { $amt.=substr($arramt[1],0,2); }

  return $amt;
  }

function create_minicalendar($date) {
  global $masterclass;

  $ret='';

  //This puts the day, month, and year in seperate variables
  $day = date('d', $date);
  $month = date('m', $date);
  $year = date('Y', $date);

  //Here we generate the first day of the month
  $first_day = mktime(0,0,0,$month, 1, $year);
  $day_of_week = date('D', $first_day);

  // Rewind to start of calendar
  switch($day_of_week){
    case "Sun": $rewind = 0; break;
    case "Mon": $rewind = 1; break;
    case "Tue": $rewind = 2; break;
    case "Wed": $rewind = 3; break;
    case "Thu": $rewind = 4; break;
    case "Fri": $rewind = 5; break;
    case "Sat": $rewind = 6; break;
  }
  //Find start of calendar
  $first_day=mktime(0,0,0,$month,(1-$rewind),$year);

  //We then determine how many days are in the current month
  $days_in_month = cal_days_in_month(0, $month, $year);

  //How many days to finish out calendar
  $total_day_count = $days_in_month+$rewind+(42-($days_in_month+$rewind));

  //Here we start building the table heads
  $ret.= "<table border=1 width=90%>";
  $ret.= '<tr><td style="text-align:center;font-weight:800;font-family:verdana,arial;">Sunday</td><td style="text-align:center;font-weight:800;font-family:verdana,arial;">Mon</td>'
  .'<td style="text-align:center;font-weight:800;font-family:verdana,arial;">Tue</td><td style="text-align:center;font-weight:800;font-family:verdana,arial;">Wed</td><td style="text-align:center;font-weight:800;font-family:verdana,arial;">Thu</td>'
  .'<td style="text-align:center;font-weight:800;font-family:verdana,arial;">Friday</td><td style="text-align:center;font-weight:800;font-family:verdana,arial;">Saturday</td></tr>';


  //This counts the days in the week, up to 7
  $week_days = 1;
  $day_count = 0;

  $ret.= "<tr valign=top>";

  //count up the days, untill we've done all of them in the month
  while
  ( $day_count < $total_day_count )
  {
  $today = $first_day+(86400*$day_count);

  if ($today==mktime(0,0,0,date("m",time()),date("d",time()),date("Y",time()))) { $bgcolor='#cccc00'; }
  else if (date("m",$today)!=date("m",mktime(0,0,0,$month,$day,$year))) { $bgcolor='#cccccc'; }
  else { $bgcolor='#ffffff'; }
  $ret.= '<td id="dayid'.$day_count.$randid.'" style="background-color:'.$bgcolor.';" OnMouseOver="document.getElementById(\'dayid'.$day_count.$randid.'\').style.background=\'#cc0000\';" OnMouseOut="document.getElementById(\'dayid'.$day_count.$randid.'\').style.background=\''.$bgcolor.'\';" OnClick="window.open(\'editcalendar.php?date='.$today.'&cal='.$cal.'\',\'\',\'height=350,width=360,toolbars=0\');"><div style="text-align:right;font-weight:800;font-family:verdana,arial;">'.date("d",$today).'</div>';
  $ret.= '<div style="text-align:left;font-size:10px;font-family:verdana,arial;">'.nl2br($data).'</div>';
  $ret.= "<br></td>";
  $day_count++;
  $week_days++;

  //Make sure we start a new row every week
  if ($week_days > 7)
  {
  $ret.= "</tr><tr>";
  $week_days = 1;
  }

  }
  $ret.= "</tr></table>";
return $ret;
}
/***************************************************************************************/
/* UPLOAD IMAGE STUFF */
/***************************************************************************************/
  function resize_image($imgpath,$maxwidth=420,$maxheight=420,$imgsave='') {
      if ($imgsave=='') { $imgsave=$imgpath; }
      $syscmd="convert $imgpath -resize ".$maxwidth."x".$maxheight." $imgsave";

      system($syscmd,$retval);

  return $retval;
  }
  function upload_image($img,$picdir='./',$picname='') {
    $debug=0;
    $gd_dump = gd_info();
    if ($debug==1) {
      if ($gd_dump['GIF Read Support']==true) { echo "Gif Good<br>";$imgtype[]=array('type'=>'image/gif','real'=>'GIF'); }
      if ($gd_dump['JPG Support']==true) { echo "JPEG Good<br>";$imgtype[]=array('type'=>'image/jpeg','real'=>'JPEG'); }
      if ($gd_dump['JPG Support']==true) { echo "JPEG Good<br>";$imgtype[]=array('type'=>'image/pjpeg','real'=>'JPEG'); }
      if ($gd_dump['PNG Support']==true) { echo "PNG Good<br>";$imgtype[]=array('type'=>'image/png','real'=>'PNG'); }
      if ($gd_dump['WBMP Support']==true) { echo "WBMP Good<br>";$imgtype[]=array('type'=>'image/bmp','real'=>'WBMP'); }
    } else {
      if ($gd_dump['GIF Read Support']==true) { $imgtype[]=array('type'=>'image/gif','real'=>'GIF'); }
      if ($gd_dump['JPG Support']==true) { $imgtype[]=array('type'=>'image/jpeg','real'=>'JPEG'); }
      if ($gd_dump['JPG Support']==true) { $imgtype[]=array('type'=>'image/pjpeg','real'=>'JPEG'); }
      if ($gd_dump['PNG Support']==true) { $imgtype[]=array('type'=>'image/png','real'=>'PNG'); }
      if ($gd_dump['WBMP Support']==true) { $imgtype[]=array('type'=>'image/bmp','real'=>'WBMP'); }
    }
/*
    // Verify correct image type
    foreach ($imgtype as $type) {
      if ($debug==1){ echo $img['type']."<br>"; }
      if ($type['type']==$img['type']) {
        if ($debug==1){ echo "Got Match--".$img['type']; }
*/
        
        if (!is_dir($picdir)) { mkdir($picdir,0755,1); }
        if (is_file($picdir.$picname.'.jpg')) { $picname.='_1';$picid=1; }
        while (is_file($picdir.$picname.'.jpg')) {
          $picid+=1;
          $picname=substr($picname,0,strlen($picname)-1).$picid;      
        }
        
        copy ($img['tmp_name'],$picdir.$picname.'.jpg');
        return $picname.'.jpg';

/*
         switch ($img['type']) {
         case 'image/gif':
          if ($imgp = imagecreatefromgif ($img['tmp_name'])) {
            break;
          } else {
            $err .= "BAD GIF IMAGE TRY AGAIN!<br>";break;
          }
         case 'image/pjpeg':
         case 'image/jpeg':
          if ($imgp = imagecreatefromjpeg ($img['tmp_name'])) {
            break;
          } else {
            $err .= "BAD JPEG IMAGE TRY AGAIN!<br>";break;
          }
         case 'image/png':
          if ($imgp = imagecreatefrompng ($img['tmp_name'])) {
            break;
          } else {
            $err .= "BAD PNG IMAGE TRY AGAIN!<br>";break;
          }
         case 'image/bmp':
          if ($imgp = imagecreatefromwbmp ($img['tmp_name'])) {
            break;
          } else {
            $err .= "BAD BMP IMAGE TRY AGAIN!<br>";break;
          }
        }
      }
    }

    if (isset($imgp) || !empty($imgp)) {

      $uploadwidth = imagesx($imgp);
      $uploadheight = imagesy($imgp);

      if (isset($picmaxheight) && isset($picmaxwidth) && $picmaxheight!='' && $picmaxwidth!='') {
        $new_width = $uploadwidth;
        $new_height = $uploadheight;
        // deal with large image first
        while ($new_width>$picmaxwidth || $new_height>$picmaxheight) {
          // figure out which dimention is futher off
          if (($new_width-$picmaxwidth) > ($new_height-$picmaxheight)) {
            // Width is larger
            $imagemultiplier = ($picmaxwidth / $new_width);
            $new_width = $picmaxwidth;
            $new_height = floor($new_height * $imagemultiplier);
          } else {
            // Height is larger
            $imagemultiplier = ($picmaxheight / $new_height);
            $new_height = $picmaxheight;
            $new_width = floor($new_width * $imagemultiplier);
          }
        }
        if ($new_width!='' || $new_height!='') {
          // Resize image
          $largeimg = imagecreatetruecolor($new_width,$new_height);
          imagecopyresampled($largeimg,$imgp,0,0,0,0,$new_width,$new_height,$uploadwidth,$uploadheight);
        } else {
          $largeimg = $imgp;
        }

        // Compile Large image JPEG
        imagejpeg($largeimg,$picdir.$picname.$picid.'.jpg',$picquality);
      }



      if ($debug==1) { echo "<center>Image ".$picdir.$img['name']." Uploaded!</center><br>"; }
    } else {
      if ($debug==1) { echo "<center>Image did not exist, Try Again</center><br>"; }
    }

    unset($imgp);
    unset($pageimg);
    unset($largeimg);
    unset($thumbimg);
*/
  return;
  }

}
?>